'use client';

import type { IPostEditInfo, IPostNewInfo } from '@/interfaces';
import { type ChangeEvent, useContext } from 'react';
import { PostEditContext } from '@/contexts/post-edit';
import useToast from '@/hooks/useToast';
import { isNum } from '@/lib/tool';
import { useMutation } from '@tanstack/react-query';
import { updatePostEditInfo } from '@/services/api';

export type TAccessSettingTranslatedField =
  | 'update'
  | 'default'
  | 'allowPlaceholder'
  | 'blockPlaceholder'
  | 'allow'
  | 'block'
  | 'closeComment'
  | 'closeReply'
  | 'closeCommentReply'
  | 'loginSee'
  | 'updateCompleted';

export default function AccessSetting({
  source,
  translatedFields = {
    update: '更新',
    default: '默认',
    allow: '白名单',
    block: '黑名单',
    closeComment: '关闭评论',
    closeReply: '关闭回复',
    closeCommentReply: '关闭评论回复',
    loginSee: '登录可见',
    allowPlaceholder: '请输入白名单用户 Id，多个用户使用逗号分隔',
    blockPlaceholder: '请输入黑名单用户 Id，多个用户使用逗号分隔',
    updateCompleted: '更新完成',
  },
}: {
  source: IPostEditInfo | IPostNewInfo;
  translatedFields?: Record<TAccessSettingTranslatedField, any>;
}) {
  const context = useContext(PostEditContext);
  const { form, setForm } = context;
  const isEdit = 'basic' in source;
  const { show } = useToast();

  const updatePostEditInfoMutation = useMutation(updatePostEditInfo);

  async function onClickUpdate() {
    if (!isEdit) {
      show({
        type: 'SUCCESS',
        message: translatedFields.updateCompleted,
      });
      return;
    }

    try {
      const _form: any = {
        otherStates: form.otherStates,
        allow: form.allow,
        block: form.block,
      };
      if (_form.allow) {
        _form.allow = _form.allow
          .filter((value: string) => isNum(value))
          .map((value: string) => parseInt(value));
      }

      if (_form.block) {
        _form.block = _form.block
          .filter((value: string) => isNum(value))
          .map((value: string) => parseInt(value));
      }

      await updatePostEditInfoMutation.mutateAsync({
        id: source.basic.id,
        data: _form,
      });
    } catch (e) {
      updatePostEditInfoMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onChange(
    e: ChangeEvent<HTMLSelectElement | HTMLInputElement | HTMLTextAreaElement>,
  ) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'otherStates') {
      let otherStates: any[];
      if (form.otherStates.find((item) => item === value)) {
        otherStates = form.otherStates.filter((item) => item !== value);
      } else {
        otherStates = [...form.otherStates, value];
      }

      setForm({
        ...form,
        otherStates,
      });
    } else if (name === 'allow') {
      setForm({
        ...form,
        allow: value.replaceAll('，', ',').split(','),
      });
    } else if (name === 'block') {
      setForm({
        ...form,
        block: value.replaceAll('，', ',').split(','),
      });
    } else {
      setForm({
        ...form,
        [name]: value,
      });
    }
  }

  return (
    <div className="card border-0">
      <div className="card-body d-flex flex-column gap-4 my-4">
        <div className="form-control user-select-none">
          <div className="form-check">
            <input
              id="yw-post-edit-otherStates-default"
              aria-label="otherStates"
              name="otherStates"
              onChange={onChange}
              className="form-check-input"
              type="checkbox"
              value="DEFAULT"
              disabled={
                form.otherStates.length > 0 &&
                !form.otherStates.includes('DEFAULT')
              }
              checked={
                form.otherStates.length === 0 ||
                form.otherStates.includes('DEFAULT')
              }
            />
            <label
              className="form-check-label"
              htmlFor="yw-post-edit-otherStates-default"
            >
              {translatedFields.default}
            </label>
          </div>
          <div className="form-check">
            <input
              id="yw-post-edit-otherStates-close-comment"
              aria-label="otherStates"
              name="otherStates"
              onChange={onChange}
              className="form-check-input"
              type="checkbox"
              value="CLOSE_COMMENT"
              disabled={form.otherStates.includes('DEFAULT')}
              checked={form.otherStates.includes('CLOSE_COMMENT')}
            />
            <label
              className="form-check-label"
              htmlFor="yw-post-edit-otherStates-close-comment"
            >
              {translatedFields.closeComment}
            </label>
          </div>
          <div className="form-check">
            <input
              id="yw-post-edit-otherStates-close-reply"
              aria-label="otherStates"
              name="otherStates"
              onChange={onChange}
              className="form-check-input"
              type="checkbox"
              value="CLOSE_REPLY"
              disabled={form.otherStates.includes('DEFAULT')}
              checked={form.otherStates.includes('CLOSE_REPLY')}
            />
            <label
              className="form-check-label"
              htmlFor="yw-post-edit-otherStates-close-reply"
            >
              {translatedFields.closeReply}
            </label>
          </div>
          <div className="form-check">
            <input
              id="yw-post-edit-otherStates-close-comment-reply"
              aria-label="otherStates"
              name="otherStates"
              onChange={onChange}
              className="form-check-input"
              type="checkbox"
              value="CLOSE_COMMENT_REPLY"
              disabled={form.otherStates.includes('DEFAULT')}
              checked={form.otherStates.includes('CLOSE_COMMENT_REPLY')}
            />
            <label
              className="form-check-label"
              htmlFor="yw-post-edit-otherStates-close-comment-reply"
            >
              {translatedFields.closeCommentReply}
            </label>
          </div>
          <div className="form-check">
            <input
              id="yw-post-edit-otherStates-login-see"
              aria-label="otherStates"
              name="otherStates"
              onChange={onChange}
              className="form-check-input"
              type="checkbox"
              value="LOGIN_SEE"
              disabled={form.otherStates.includes('DEFAULT')}
              checked={form.otherStates.includes('LOGIN_SEE')}
            />
            <label
              className="form-check-label"
              htmlFor="yw-post-edit-otherStates-login-see"
            >
              {translatedFields.loginSee}
            </label>
          </div>
          <div className="form-check">
            <input
              id="yw-post-edit-otherStates-allow"
              aria-label="otherStates"
              name="otherStates"
              onChange={onChange}
              className="form-check-input"
              type="checkbox"
              value="ALLOW"
              disabled={form.otherStates.includes('DEFAULT')}
              checked={form.otherStates.includes('ALLOW')}
            />
            <label
              className="form-check-label"
              htmlFor="yw-post-edit-otherStates-allow"
            >
              {translatedFields.allow}
            </label>
          </div>
          <div className="form-check">
            <input
              id="yw-post-edit-otherStates-block"
              aria-label="otherStates"
              name="otherStates"
              onChange={onChange}
              className="form-check-input"
              type="checkbox"
              value="BLOCK"
              disabled={form.otherStates.includes('DEFAULT')}
              checked={form.otherStates.includes('BLOCK')}
            />
            <label
              className="form-check-label"
              htmlFor="yw-post-edit-otherStates-block"
            >
              {translatedFields.block}
            </label>
          </div>
        </div>

        {form.otherStates.includes('ALLOW') && (
          <textarea
            rows={1}
            className="form-control"
            name="allow"
            value={form.allow}
            onChange={onChange}
            placeholder={translatedFields.allowPlaceholder}
          />
        )}

        {form.otherStates.includes('BLOCK') && (
          <textarea
            rows={1}
            className="form-control"
            name="block"
            value={form.block}
            onChange={onChange}
            placeholder={translatedFields.blockPlaceholder}
          />
        )}

        <div className="d-grid col-2">
          <button
            onClick={onClickUpdate}
            type="button"
            className="btn btn-success"
          >
            {translatedFields.update}
          </button>
        </div>
      </div>
    </div>
  );
}
